package com.hll.javaweb.servlet.basic;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.MalformedURLException;

/**
 * @author hll
 * @create 2022-05-10 11:15
 */
@WebServlet("/hello-context")
public class HelloContext extends HttpServlet {
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
    System.out.println(getServletContext().getAttribute("attr1"));
  }

  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws MalformedURLException {
    // context整个项目只有一个，全局有效
    ServletContext servletContext = this.getServletContext();
    // 2. 读取 servletContext 的初始化参数---在web.xml中
    System.out.println(servletContext.getInitParameter("username"));
    // 3. 读取另一个参数
    System.out.println(servletContext.getInitParameter("password"));

    // 可以获取到 resources/下的文件,不推荐！，建议使用 classLoader，并且非servlet类无法获取context
    // servletContext.getRealPath("/WEB-INF/classes/db.properties");
    // webapp下的文件
    // System.out.println(servletContext.getRealPath("upload/艾斯.jpg"));
    servletContext.setAttribute("attr1", "哈哈");
  }
}
